package net.zjitc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.zjitc.entity.Permission;
import net.zjitc.entity.Vo.PermissionVo;
import net.zjitc.mapper.PermissionMapper;
import net.zjitc.mapper.RoleMapper;
import net.zjitc.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Transactional
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired(required = false)
    private PermissionMapper permissionMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Override
    public List<PermissionVo> selectAll() {

        return permissionMapper.selectList(null);
    }

    @Override
    public List<PermissionVo> getTree() {

        List<PermissionVo> oneList=getPermissionByLeavel("0");
        List<PermissionVo> twoList=getPermissionByLeavel("1");
        List<PermissionVo> threeList=getPermissionByLeavel("2");
        getPermissions(twoList,threeList);
        getPermissions(oneList,twoList);
        return oneList;
    }

    @Override
    public List<PermissionVo> getMenus() {
        List<PermissionVo> oneList=new ArrayList<>();
        List<PermissionVo> twolist=new ArrayList<>();
        List<PermissionVo> permissionList = permissionMapper.selectList(null);
        for (PermissionVo permission: permissionList
             ) {
            String path= permissionMapper.selectPath(permission.getId());
            permission.setPath(path);
            if (permission.getLevel().equals("0")){
                oneList.add(permission);
            }else if (permission.getLevel().equals("1")){
                twolist.add(permission);
            }
        }

        getPermissions(oneList,twolist);
        return oneList;
    }

    private List<PermissionVo> getPermissionByLeavel(String type){
        QueryWrapper<PermissionVo> wrapper=new QueryWrapper<>();
        wrapper.eq("ps_level",type);
        List<PermissionVo> list=permissionMapper.selectList(wrapper);
        return list;
    }
    private void getPermissions(List<PermissionVo> Parent_node, List<PermissionVo> Child_node) {
        for (PermissionVo Parent: Parent_node ){
            List<PermissionVo> temp=new ArrayList<>();
            for (PermissionVo Child: Child_node){
                if(Child.getPid().intValue()==Parent.getId().intValue()){
                    temp.add(Child);
                }
            }
            Parent.setChildren(temp);
        }

    }
}
